import time
from datetime import datetime
from os import times

from appium.options.android import UiAutomator2Options
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


# class CommonDriver:
#     def get_driver(self):
#         options = UiAutomator2Options()
#         options.platform_name = 'Android'
#         options.platform_version = '7'
#         options.app_package = 'com.dangdang.buy2'
#         # options.app_package = 'com.microvirt.launcher2'
#         options.app_activity = 'com.dangdang.buy2.StartupActivity'
#         # options.app_activity = 'com.microvirt.launcher.Launcher'
#         options.no_reset = False
#         options.unicode_keyboard = True
#         options.udid = '127.0.0.1:21513'
#
#         command_executor_url = "http://127.0.0.1:4723/wd/hub"
#
#         driver = webdriver.Remote(command_executor=command_executor_url, options=options)
#
#         driver.implicitly_wait(10)
#
#         print("连接成功")
#
#         return driver
class CommonDriver:
    def get_driver(self, udid, port):
        options = UiAutomator2Options()
        options.platform_name = 'Android'
        options.platform_version = '7'
        options.app_package = 'com.dangdang.buy2'
        options.app_activity = 'com.dangdang.buy2.StartupActivity'
        options.no_reset = False
        options.unicode_keyboard = True
        options.udid = udid  # 动态传入设备ID

        command_executor_url = f"http://127.0.0.1:{port}/wd/hub"

        driver = webdriver.Remote(command_executor=command_executor_url, options=options)
        driver.implicitly_wait(10)
        print(f"设备 {udid} 连接成功，Appium端口 {port}")
        return driver


if __name__ == '__main__':
    driver = CommonDriver().get_driver()
    driver.find_element(AppiumBy.XPATH,
                        '//android.widget.TextView[@resource-id="com.dangdang.buy2:id/tv_sure"]').click()
    current_time = datetime.now()
    print("当前时间为：", current_time)
    try:
        element = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located(
                (AppiumBy.XPATH, '//android.widget.TextView[@resource-id="com.dangdang.buy2:id/tv_sur"]')
            )
        )
        element.click()
    except BaseException as e:
        print(e)
    finally:
        current_time = datetime.now()
        print("当前时间为：", current_time)
